package com.iwhalecloud.uncc.web.service;

import com.iwhalecloud.uncc.archiver.Archiver;
import com.iwhalecloud.uncc.archiver.impl.InsCollectServerArchiver;
import com.iwhalecloud.uncc.archiver.impl.InsCollectServiceArchiver;
import com.iwhalecloud.uncc.archiver.impl.InsCollectTaskArchiver;
import com.iwhalecloud.uncc.common.ArchiverConstant;
import com.iwhalecloud.uncc.common.ArchiverThreadLocal;
import com.iwhalecloud.uncc.scheduler.DynamicScheduler;
import com.iwhalecloud.uncc.scheduler.ScheduleTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;


/**
 * @author zq
 * @date 2021/10/15 12:14
 * @description SchedulerService
 */
@Service
@Slf4j
public class ScheduleService implements WebService{

    @Autowired
    private DynamicScheduler dynamicScheduler;


    @Override
    public boolean archiveAll(){
        this.archiveInsCollectTask();
        this.archiveInsCollectService();
        this.archiveInsCollectServer();
        return true;
    }

    @Override
    public boolean archiveInsCollectTask() {
        return this.archive(ArchiverConstant.INS_COLLECT_TASK,new InsCollectTaskArchiver());
    }

    @Override
    public boolean archiveInsCollectService() {
        return this.archive(ArchiverConstant.INS_COLLECT_SERVICE,new InsCollectServiceArchiver());
    }

    @Override
    public boolean archiveInsCollectServer() {
        return this.archive(ArchiverConstant.INS_COLLECT_SERVER,new InsCollectServerArchiver());
    }

    private boolean archive(String task , Archiver archiver){
        ScheduleTask scheduleTask = new ScheduleTask(task + "_" + UUID.randomUUID().toString(),archiver);
        String cron = ArchiverThreadLocal.getArchiveParam().getCron();
        boolean isStart = dynamicScheduler.start(scheduleTask, cron);
        if(isStart){
            if(log.isInfoEnabled()){
                log.info("归档定时任务启动,任务ID:"+scheduleTask.getId()+",任务cron:"+cron);
            }
            return true;
        }else{
            return false;
        }
    }
}
